package com.ming.attendance.controller;

import com.ming.attendance.service.ExportReportService;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/ExportReport")
public class ExportReportController {
    @Autowired
    ExportReportService ers;

    @GetMapping("/getReportByExcel")
    public void getReportByExcel(@RequestHeader("eventid") String eventid, HttpServletResponse response){

        // 因为是通过wx.downloadFile()发起的请求，所以通过header传输和接受参数
        // String eventid = request.getHeader("eventid");

        XSSFWorkbook wb = ers.getReportByExcel(eventid);
        // String sheetName = wb.getSheetName(0);
        String fileName = wb.getSheetName(0) + "_数据报表.xlsx";
        OutputStream outputStream = null;
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            // 设置ContentType请求信息格式
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
